package com.ybg.engine.config;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 教学时间Helper
 * 
 * @author lishiwei
 * @data 2017年5月24日
 *
 */
public class ScheduleTimeHelper {

	private SystemConfigHolder systemConfigHolder;

	private Map<String, Object> configs;
	
	public ScheduleTimeHelper(JdbcTemplate jdbcTemplate){
		systemConfigHolder = new SystemConfigHolder(jdbcTemplate);
	}

	/* 学年 */
	public String getCurrentYear() {
		return getConfigs().get("currentYear").toString();
	}

	/* 学期 */
	public String getCurrentTerm() {
		return getConfigs().get("currentTerm").toString();
	}

	/* 学期开始日期 */
	public Date getStartDay() {
		String day = getConfigs().get("startDay").toString();
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return format.parse(day);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	/* 学期结束日期 */
	public Date getEndDay() {
		String day = getConfigs().get("endDay").toString();
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return format.parse(day);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	/* 教学周 */
	public int getCycle(Date date) {
		Calendar cale = Calendar.getInstance();
		cale.setTime(getStartDay());
		long startTime = cale.getTimeInMillis();

		return (int) ((date.getTime() - startTime) / (1000 * 60 * 60 * 24 * 7)) + 1;
	}

	/* 最大教学周/学期总周次 */
	public int getLastCycle() {
		return getCycle(getEndDay());
	}

	private Map<String, Object> getConfigs() {
		if (configs == null) {
			synchronized (ScheduleTimeHelper.class) {
				if (configs == null) {
					loadConfigs();
				}
			}
		}
		return configs;
	}

	private void loadConfigs() {
		configs = new HashMap<String, Object>();
		// 学年 学期
		String[] yearAndTerm = systemConfigHolder.getStringValue("schedule_currentTermToShow").split(",");
		configs.put("currentYear", yearAndTerm[0]);
		configs.put("currentTerm", yearAndTerm[1]);
		// 开始时间 结束时间
		String[] times = systemConfigHolder.getStringValue("schedule_currentTermDateToShow").split(",");
		configs.put("startDay", times[0]);
		configs.put("endDay", times[1]);
	}

}
